<template>
  <div class="registerDetail">
    <van-nav-bar
      :fixed="true"
      :placeholder="true"
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 表单 -->
    <div class="formData">
      <van-form ref="form">
        <van-field
          v-model="dataSource.fixNumberName"
          name="维修中心"
          label="维修中心"
          input-align="right"
          placeholder="请选择"
          right-icon="arrow"
          @click="handleSelect('fixNumber', 'fixNumberName', 'fixId')"
          :rules="[{ required: true }]"
          readonly
        />
        <van-field
          v-model="dataSource.brandNumberName"
          readonly
          name="品牌"
          label="品牌"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('brandNumber', 'brandNumberName', 'brandId')"
        />
        <van-field
          v-model="dataSource.hallNumberName"
          readonly
          name="展厅"
          label="展厅"
          input-align="right"
          placeholder="请选择"
          :rules="[{ required: true }]"
          right-icon="arrow"
          @click="handleSelect('hallNumber', 'hallNumberName', 'hallId')"
        />
        <van-field name="radio" label="保险类型" input-align="right">
          <template #input>
            <van-radio-group
              v-model="dataSource.insType"
              direction="horizontal"
            >
              <van-radio
                :name="item.value"
                v-for="(item, index) in insuranceList"
                :key="index"
              >
                {{ item.name }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="uploader" label="商业险" input-align="right">
          <template #input>
            <van-uploader
              v-model="uploader"
              :after-read="comInsFileUpload"
              :max-count="1"
              accept=".pdf"
              @delete="(file, detail) => delComInsFile(file, detail)"
            >
              <van-button icon="plus" type="info" size="small">上传</van-button>
              <!-- <template>
                <div class="preview-cover van-ellipsis">{{ file.name }}</div>
              </template> -->
            </van-uploader>
          </template>
        </van-field>
        <van-field name="uploader" label="交强险" input-align="right">
          <template #input>
            <van-uploader
              v-model="uploader1"
              :after-read="trafficFileUpload"
              :max-count="1"
              accept=".pdf"
              @delete="(file, detail) => delTrafficFile(file, detail)"
            >
              <van-button icon="plus" type="info" size="small">上传</van-button>
            </van-uploader>
          </template>
        </van-field>

        <!-- 下拉选择弹窗 -->
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-field
            name="模糊查询"
            input-align="left"
            v-model="likeWho"
            label="模糊查询"
            v-if="
              likeWhoField == 'fixNumber'
            "
            placeholder="请输入模糊查询关键词"
          />
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="handleSelectConfirm"
            @cancel="showSelectPicker = false"
            value-key="name"
          />
        </van-popup>
      </van-form>
    </div>
    <div class="addBtn">
      <div class="flex">
        <div class="footerBtn comfirmBtn" @click.stop="formOnSubmit">确认</div>
        <div class="footerBtn cancelBtn" @click.stop="goUploadRecord">
          上传记录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Search, Empty, Field, Form, Uploader, Notify ,Toast} from 'vant'
import { getCookies } from '../../utils/util'
import commonApi from '@/api/commonApi'
import policyApi from '@/api/policyApi'
export default {
  name: 'policyRobot',
  components: {
    Search,
    Empty,
    Field,
    Form,
    Uploader,
    Notify,
    Toast
  },
  data() {
    return {
      showTimerPicker: false,
      dataSource: {
        fixNumber: '',
        fixNumberName: '',
        fixId: '',
        brandNumber: '',
        brandNumberName: '',
        files: [],
        hallNumber: '',
        hallNumberName: '',
        insType: '续保',
      },
      uploader: [],
      uploader1: [],
      columns: [],
      showSelectPicker: false,
      disabled: false,
      field: '',
      fieldName: '',
      fieldId: '',
      showMultipleVisible: false,
      empList: [],
      userId: getCookies('userId'),
      fixCenterList: [],
      showOrgList: [],
      brandList: [],
      insuranceList: [
        { name: '续保', value: '续保' },
        { name: '新车投保', value: '新车投保' },
      ],
      comInsFile: '', //商业险
      trafficFile: '', //交强险
      likeWhoField:"",
      likeWho:''
    }
  },
  watch: {
    likeWho: function (nval, oval) {
      if (this.likeWhoField == 'fixNumber') {
        if (nval) {
          let newArr = this.fixCenterList.filter((item) => {
            return item.name.indexOf(nval) > -1
          })
          console.log(newArr)
          this.columns = newArr
        }else{
          this.columns = this.fixCenterList
        }
      }
    },
  },
  mounted() {
    this.getMainFixCenter()
    // this.getInsurance();
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },

    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          userId: this.userId,
          type: 'fixCenter',
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data
          }
        })
    },
    // 获取品牌
    getBrandByFixCenter() {
      commonApi
        .getBrandByFixCenter({
          fixCenterId: this.dataSource.fixId,
        })
        .then((res) => {
          if (res.data) {
            this.brandList = res.data
            this.brandList.forEach((el)=>{
              if(this.dataSource.brandId==el.billId){
                this.dataSource.brandNumber = el.number;
              }
            })
          }
        })
    },
    // 获取展厅
    getShowOrgByFixCenterId() {
      commonApi
        .getShowOrgByFixCenterId({
          fixCenterId: this.dataSource.fixId,
        })
        .then((res) => {
          if (res.data) {
            this.showOrgList = res.data
            this.showOrgList.forEach((el)=>{
              if(this.dataSource.hallId==el.billId){
                this.dataSource.hallNumber = el.number;
              }
            })
          }
        })
    },
    // 获取保险类型
    getInsurance() {
      commonApi
        .getEnums({
          key: 'insurance',
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insuranceList = res.data
            this.dataSource.insurance = res.data[0].value
          }
        })
    },

    // 选择下拉
    handleSelect(field, fieldName, fieldId) {
      if (field == 'fixNumber') {
        this.columns = this.fixCenterList
      } else if (field == 'brandNumber') {
        if (!this.dataSource.fixNumber) {
          Toast('请先选择维修中心')
          return;
        }
        this.columns = this.brandList
      } else if (field == 'hallNumber') {
        if (!this.dataSource.fixNumber) {
          Toast('请先选择维修中心')
          return;
        }
        this.columns = this.showOrgList
      }
      this.field = field
      this.fieldName = fieldName
      this.fieldId = fieldId
      this.likeWhoField = field
      this.showSelectPicker = true

    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.dataSource[this.field] = value.number
      this.dataSource[this.fieldName] = value.name
      this.dataSource[this.fieldId] = value.billId
      if (this.field == 'fixNumber') {
        this.fixNumber = ''
        this.fixNumberName = ''
        this.brandNumber = ''
        this.brandNumberName = ''
        this.getBrandByFixCenter()
        this.getShowOrgByFixCenterId()
        this.fixCenterList.forEach((item) => {
          if (item.billId == value.billId) {
            this.dataSource.brandId = item.brandId;
            this.dataSource.brandNumberName = item.brandName;
            this.dataSource.hallId = item.showOrgId;
            this.dataSource.hallNumberName = item.showOrgName;
          }
        });
        console.log(this.dataSource);
      }
      this.likeWho = ''
      this.showSelectPicker = false
    },

    comInsFileUpload(file) {
      console.log(file)
      this.comInsFile = file.file
    },
    trafficFileUpload(file) {
      this.trafficFile = file.file
    },
    delComInsFile() {
      this.comInsFile = ''
    },
    delTrafficFile() {
      this.trafficFile = ''
    },
    goUploadRecord() {
      this.$router.push('/policyRobotRecord')
    },
    formOnSubmit() {
      this.$refs.form.validate().then(() => {
        let formData = new FormData()
        if (!this.comInsFile && !this.trafficFile) {
          Notify({ type: 'danger', message: '商业险或交强险必传一项' })
          return
        }
        if (this.comInsFile) {
          const copyComInsFile = new File([this.comInsFile], '商业险.pdf')
          formData.append('files', copyComInsFile)
        }
        if (this.trafficFile) {
          const copyTrafficFile = new File([this.comInsFile], '商业险.pdf')
          formData.append('files', copyTrafficFile)
        }
        formData.append('brandNumber', this.dataSource.brandNumber)
        formData.append('hallNumber', this.dataSource.hallNumber)
        formData.append('fixNumber', this.dataSource.fixNumber)
        formData.append('insType', this.dataSource.insType)

        policyApi.uploadFlies(formData).then((res) => {
          if (res.errmsg == 'ok') {
            Notify({ type: 'success', message: '上传成功，请等待机器人录单' })
            this.uploader = []
            this.uploader1 = []
            this.delComInsFile()
            this.delTrafficFile()
          }
        })
      })
      // .catch(() => {
      //   this.$toast.fail("请完善信息");
      // });
    },
  },
}
</script>

<style lang="less" scoped>
.flex {
  display: flex;
  align-items: center;
}
.registerDetail {
  background: #fff;
  overflow: hidden;
  .detail_header {
    justify-content: space-between;
    margin: 0.2rem 0.2rem;
    border-radius: 5px;
    background: #fff;
    padding: 0.3rem;
    .detail_header_lt {
      .carNo {
        font-size: 0.32rem;
        font-weight: bold;
        margin-bottom: 0.2rem;
        .icon-right {
          margin-left: 0.2rem;
          color: #409eff;
        }
      }
      .hank {
        font-size: 0.28rem;
        color: #666;
      }
    }
    .detail_header_rt {
      justify-content: flex-start;
      .txt {
        font-size: 0.28rem;
        color: #161616;
      }
      .icon-tel {
        color: #fff;
        background: #35bc04;
        font-size: 0.32rem;
        padding: 0.1rem;
        border-radius: 50%;
        margin-right: 0.1rem;
      }
    }
  }
  .formData {
    // background: #fff;
  }
}
/deep/.van-field__error-message {
  text-align: right;
}

.addBtn {
  // position: fixed;
  margin-top: 0.5rem;
  bottom: 0.8rem;
  width: 100%;
  z-index: 1;
  .footerBtn {
    width: 2.8rem;
    margin: auto;
    text-align: center;
    font-size: 0.28rem;
    padding: 0.25rem 0rem;
    border-radius: 50px;
  }
  .orderItem_filebox {
    margin: auto;
    background: #409eff;
    color: #fff;
  }
  .comfirmBtn {
    background: #409eff;
    color: #fff;
  }
  .cancelBtn {
    color: #fff;
    background: #35bc04;
  }
}
</style>
